package com.news.admin.service.imp;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.news.admin.mapper.LoginMapper;
import com.news.admin.service.LoginService;
import com.news.model.admin.dtos.AdUserDto;
import com.news.model.admin.pojos.AdUser;
import com.news.model.common.dtos.ResponseResult;
import com.news.model.common.enums.AppHttpCodeEnum;
import com.news.utils.common.AppJwtUtil;
import com.news.utils.common.MD5Utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.Map;

/**
 * 管理员登录
 */
@Service
@Slf4j
@Transactional
public class LoginServiceImp extends ServiceImpl<LoginMapper, AdUser> implements LoginService {

    @Autowired
    private LoginMapper loginMapper;

    /**
     * 管理员登录
     * @param dto
     * @return
     */
    @Override
    public ResponseResult login(AdUserDto dto) {

        if (dto == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }
        AdUser adUser = loginMapper.selectOne(Wrappers.<AdUser>lambdaQuery()
                .eq(AdUser::getName, dto.getName())
        );
        if (adUser == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST,"用户不存在");
        }
        String pwd = dto.getPassword()+adUser.getSalt();
        pwd = MD5Utils.encode(pwd);
        if (!adUser.getPassword().equals(pwd)){
            return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
        }
        Long aLong = Long.valueOf(adUser.getId());
        String token = AppJwtUtil.getToken(aLong);
        adUser.setPassword(null);
        adUser.setSalt(null);
        Map<String,Object> map =new HashMap<>();
        map.put("user",adUser);
        map.put("token",token);

        return ResponseResult.okResult(map);
    }

    public static void main(String[] args) {
        System.out.println(MD5Utils.encode("123456123abc"));
    }
}
